package com.danceforyou.medium.controller;

import com.danceforyou.common.model.view.BizData4Page;
import com.danceforyou.common.restful.exception.BizExceptionEnum;
import com.danceforyou.common.util.AssertUtil;
import com.danceforyou.common.util.Constants;
import com.danceforyou.common.util.ExcelExportUtil;
import com.danceforyou.common.util.StringUtil;
import com.danceforyou.common.vo.MediumExcelVO;
import com.danceforyou.common.vo.MediumVideoExcelVO;
import com.danceforyou.common.vo.SqlOrderEnum;
import com.danceforyou.medium.model.MediumDO;
import com.danceforyou.medium.model.MediumLabelDO;
import com.danceforyou.medium.service.MediumLabelService;
import com.danceforyou.medium.service.MediumService;
import com.danceforyou.medium.service.MediumVoucherService;
import com.danceforyou.medium.vo.MediumLabelVO;
import com.danceforyou.medium.vo.MediumVO;
import com.danceforyou.payment.vo.PaymentExcelVO;
import com.danceforyou.payment.vo.PaymentVO;
import com.danceforyou.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/medium")
public class MediumController {

    @Autowired
    private MediumService mediumService;
    @Autowired
    private MediumLabelService mediumLabelService;
    @Autowired
    private MediumVoucherService mediumVoucherService;
    @Autowired(required = false)
    private HttpSession session;

    /**
     * 分页查询公众号类别列表
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryMediumLabelPage", method = RequestMethod.GET)
    public BizData4Page<MediumLabelVO> queryMediumLabelPage(BizData4Page<MediumLabelVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            if (StringUtil.isBlank(entry.getValue().toString())) {
                condition.put(entry.getKey(), null);
            }
        }
        mediumLabelService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 查询公众号类别列表
     * @return List<MediumLabelDO>
     */
    @RequestMapping(value = "/getMediumLabelList", method = RequestMethod.GET)
    public List<MediumLabelDO> getMediumLabelList(String type) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        return mediumLabelService.listByProperty("type", type, "id", SqlOrderEnum.ASC);
    }

    /**
     * 新建公众号类别
     * @param mediumLabel 公众号类别信息
     * @return boolean
     */
    @RequestMapping(value = "/saveMediumLabelInfo", method = RequestMethod.POST)
    public boolean saveMediumLabelInfo(MediumLabelDO mediumLabel) {
        mediumLabelService.saveInfo(mediumLabel);
        return true;
    }

    /**
     * 删除公众号类别
     * @param ids 公众号类别IDS
     * @return boolean
     */
    @RequestMapping(value = "/deleteMediumLabelInfoByIds", method = RequestMethod.POST)
    public int deleteMediumLabelInfoByIds(String ids) {
        return mediumLabelService.deleteInfoByIds(ids);
    }

    /**
     * 处理公众号查询条件
     * @param condition 查询条件
     */
    public void dealMediumCondition(Map<String, Object> condition) {
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            if (StringUtil.isBlank(entry.getValue().toString())) {
                condition.put(entry.getKey(), null);
            }
        }
        if (condition.get("numberType") != null) {
            switch (condition.get("numberType").toString()) {
                case "1":
                    //粉丝数量
                    if (condition.get("numberStart") != null) {
                        condition.put("fansSheetsStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("fansSheetsEnd", condition.get("numberEnd"));
                    }
                    break;
                case "2":
                    //男粉比例
                    if (condition.get("numberStart") != null) {
                        condition.put("manRatioStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("manRatioEnd", condition.get("numberEnd"));
                    }
                    break;
                case "3":
                    //女粉比例
                    if (condition.get("numberStart") != null) {
                        BigDecimal womanRatioStart = new BigDecimal(condition.get("numberStart").toString());
                        condition.put("manRatioEnd", new BigDecimal(100).subtract(womanRatioStart));
                    }
                    if (condition.get("numberEnd") != null) {
                        BigDecimal womanRatioEnd = new BigDecimal(condition.get("numberEnd").toString());
                        condition.put("manRatioStart", new BigDecimal(100).subtract(womanRatioEnd));
                    }
                    break;
                case "4":
                    //头条执行价
                    if (condition.get("numberStart") != null) {
                        condition.put("headLineQuotedStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("headLineQuotedEnd", condition.get("numberEnd"));
                    }
                    break;
                case "5":
                    //次条执行价
                    if (condition.get("numberStart") != null) {
                        condition.put("secondLineQuotedStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("secondLineQuotedEnd", condition.get("numberEnd"));
                    }
                    break;
                case "6":
                    //三条执行价
                    if (condition.get("numberStart") != null) {
                        condition.put("thirdLineQuotedStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("thirdLineQuotedEnd", condition.get("numberEnd"));
                    }
                    break;
                case "7":
                    //尾条执行价
                    if (condition.get("numberStart") != null) {
                        condition.put("tailLineQuotedStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("tailLineQuotedEnd", condition.get("numberEnd"));
                    }
                    break;
                case "8":
                    //头条成本价
                    if (condition.get("numberStart") != null) {
                        condition.put("headLineCostStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("headLineCostEnd", condition.get("numberEnd"));
                    }
                    break;
                case "9":
                    //次条成本价
                    if (condition.get("numberStart") != null) {
                        condition.put("secondLineCostStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("secondLineCostEnd", condition.get("numberEnd"));
                    }
                    break;
                case "10":
                    //三条成本价
                    if (condition.get("numberStart") != null) {
                        condition.put("thirdLineCostStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("thirdLineCostEnd", condition.get("numberEnd"));
                    }
                    break;
                case "11":
                    //尾条成本价
                    if (condition.get("numberStart") != null) {
                        condition.put("tailLineCostStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("tailLineCostEnd", condition.get("numberEnd"));
                    }
                    break;
                case "12":
                    //返点比例
                    if (condition.get("numberStart") != null) {
                        condition.put("rebatesRateStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("rebatesRateEnd", condition.get("numberEnd"));
                    }
                    break;
                default: break;
            }
        }
        if (condition.get("mediumUserId") != null && condition.get("mediumUserId").toString().equals("ALL")) {
            condition.put("mediumUserId", null);
        }
    }

    /**
     * 分页查询我的公众号列表
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/querySelfMediumPage", method = RequestMethod.GET)
    public BizData4Page<MediumVO> querySelfMediumPage(BizData4Page<MediumVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealMediumCondition(condition);
        if (!loginUser.getRole().getRoleType().equals(Constants.ROLE_GLB_CODE)) {
            condition.put("createUserId", loginUser.getId());
        }
        condition.put("isDelete", false);
        mediumService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 分页查询公众号列表
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryMediumPage", method = RequestMethod.GET)
    public BizData4Page<MediumVO> queryMediumPage(BizData4Page<MediumVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealMediumCondition(condition);
        condition.put("isDelete", false);
        mediumService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 新建公众号
     * @param medium 公众号信息
     * @return boolean
     */
    @RequestMapping(value = "/saveMediumInfo", method = RequestMethod.POST)
    public boolean saveMediumInfo(MediumDO medium) {
        mediumService.saveInfo(medium);
        return true;
    }

    /**
     * 修改公众号
     * @param medium 公众号信息
     * @return boolean
     */
    @RequestMapping(value = "/updateMediumInfo", method = RequestMethod.POST)
    public boolean updateMediumInfo(MediumDO medium) {
        mediumService.updateInfo(medium);
        return true;
    }

    /**
     * 删除公众号
     * @param ids 公众号IDS
     * @return boolean
     */
    @RequestMapping(value = "/deleteMediumInfoByIds", method = RequestMethod.POST)
    public int deleteMediumInfoByIds(String ids) {
        return mediumService.deleteInfoByIds(ids);
    }

    /**
     * 转授公众号
     * @param mediumIds 公众号IDS
     * @param mediumUserId 目标员工ID
     * @return int
     */
    @RequestMapping(value = "/delegateMediumInfo", method = RequestMethod.POST)
    public int delegateMediumInfo(String mediumIds, Long mediumUserId) {
        return mediumService.saveDelegateMediumInfo(mediumIds, mediumUserId);
    }

    /**
     * 上传公众号用户画像
     * @param fileList 文件列表
     * @param mediumId 公众号ID
     * @return boolean
     */
    @RequestMapping(value = "/saveMediumVoucher", method = RequestMethod.POST)
    public boolean saveMediumVoucher(@RequestParam MultipartFile[] fileList, Long mediumId) {
        mediumVoucherService.saveMediumVoucher(fileList, mediumId);
        return true;
    }

    /**
     * 获取公众号用户画像
     * @param mediumId 公众号ID
     * @return String
     */
    @RequestMapping("/listVoucherByMediumId")
    public String listVoucherByMediumId(Long mediumId) {
        String ossFileIds = mediumVoucherService.listVoucherByMediumId(mediumId);
        AssertUtil.notNull(ossFileIds, "该公众号暂未上传用户画像");
        return ossFileIds;
    }

    /**
     * 批量上传公众号信息
     * @param file 公众号文件
     * @return int
     */
    @RequestMapping(value = "/uploadMediumInfos", method = RequestMethod.POST)
    public int uploadMediumInfos(MultipartFile file) {
        AssertUtil.notNull(file, "请选择excel文件");
        AssertUtil.isTrue(file.getOriginalFilename().endsWith(".xlsx"), "请选择xls格式文件");
        return mediumService.saveUploadMediumInfos(file);
    }

    /**
     * 批量上传视频号信息
     * @param file 公众号文件
     * @return int
     */
    @RequestMapping(value = "/uploadMediumVideoInfos", method = RequestMethod.POST)
    public int uploadMediumVideoInfos(MultipartFile file) {
        AssertUtil.notNull(file, "请选择excel文件");
        AssertUtil.isTrue(file.getOriginalFilename().endsWith(".xlsx"), "请选择xls格式文件");
        return mediumService.saveUploadMediumVideoInfos(file);
    }

    /**
     * 根据公众号ID获取公众号收款信息
     * @param mediumId 公众号ID
     * @return MediumVO
     */
    @RequestMapping(value = "/getMediumReceiptInfoById", method = RequestMethod.GET)
    public MediumVO getMediumReceiptInfoById(Long mediumId) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        MediumDO medium = mediumService.getById(mediumId);
        AssertUtil.notNull(medium, "公众号信息不存在");
        MediumVO mediumVO = new MediumVO();
        mediumVO.setRecName(medium.getRecName());
        mediumVO.setRecBank(medium.getRecBank());
        mediumVO.setRecAccount(medium.getRecAccount());
        return mediumVO;
    }

    /**
     * 导出公众号信息
     * @param condition 查询条件
     */
    @RequestMapping(value = "/exportMedium", method = RequestMethod.GET)
    public void exportMedium(@RequestParam Map<String, Object> condition, HttpServletResponse response) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        dealMediumCondition(condition);
        condition.put("isDelete", false);
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_MJB_CODE) || loginUser.getRole().getRoleType().equals(Constants.ROLE_XSB_CODE)) {
            condition.putIfAbsent("mediumUserId", loginUser.getId());
        }
        List<MediumVO> mediumList = mediumService.queryList(condition, condition.get("orderBy").toString(), condition.get("sortBy").toString().equals("ASC") ? SqlOrderEnum.ASC : SqlOrderEnum.DESC);
        List<Object> excelVOList = new ArrayList<>();
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MediumVO medium : mediumList) {
            MediumExcelVO excelVO = new MediumExcelVO();
            excelVO.setId(medium.getId());
            excelVO.setLabel(medium.getLabel());
            excelVO.setName(medium.getName());
            excelVO.setWeChatNo(medium.getWeChatNo());
            excelVO.setFansSheets(medium.getFansSheets());
            excelVO.setManRatio(medium.getManRatio());
            excelVO.setHeadLineQuoted(medium.getHeadLineQuoted());
            excelVO.setSecondLineQuoted(medium.getSecondLineQuoted());
            excelVO.setThirdLineQuoted(medium.getThirdLineQuoted());
            excelVO.setTailLineQuoted(medium.getTailLineQuoted());
            excelVO.setHeadLineCost(medium.getHeadLineCost());
            excelVO.setSecondLineCost(medium.getSecondLineCost());
            excelVO.setThirdLineCost(medium.getThirdLineCost());
            excelVO.setTailLineCost(medium.getTailLineCost());
            excelVO.setCreateUserName(medium.getCreateUserName());
            if (medium.getBillPoint() < 0) {
                excelVO.setBillPoint("普票" + (-medium.getBillPoint()) + "%");
            } else if (medium.getBillPoint() == 0) {
                excelVO.setBillPoint("不含票");
            } else {
                excelVO.setBillPoint("专票" + medium.getBillPoint() + "%");
            }
            excelVO.setBillPoint(dateTimeFormat.format(medium.getCreateDate()));
            excelVO.setRefuseType(medium.getRefuseType());
            excelVO.setBrushType(medium.getBrushType());
            excelVO.setCreateUserName(medium.getCreateUserName());
            excelVO.setUpdateDate(dateTimeFormat.format(medium.getUpdateDate()));
            excelVO.setOrderCount(medium.getOrderCount());
            excelVO.setCreateDesc(medium.getCreateDesc());
            excelVOList.add(excelVO);
        }
        String[] fieldTitle = {"公众号编号", "公众号类别", "公众号名称", "微信号", "粉丝数量(万)", "粉丝年龄段", "男粉比例", "头条执行价", "次条执行价", "三条执行价",
                "尾条执行价", "头条成本价", "次条成本价", "三条成本价", "尾条成本价", "发票税点", "拒接广告类型", "刷号类型", "对接员工", "更新时间",
                "合作排期数", "备注信息"};
        int[] fieldWidth = {10, 15, 20, 20, 10, 10, 10, 10, 10, 10,
                10, 10, 10, 10, 10, 10, 40, 10, 10, 20,
                10, 40};
        ExcelExportUtil.export("公众号列表", fieldTitle, fieldWidth, excelVOList, response);
    }

    /**
     * 导出视频号信息
     * @param condition 查询条件
     */
    @RequestMapping(value = "/exportMediumVideo", method = RequestMethod.GET)
    public void exportMediumVideo(@RequestParam Map<String, Object> condition, HttpServletResponse response) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        dealMediumCondition(condition);
        condition.put("isDelete", false);
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_MJB_CODE) || loginUser.getRole().getRoleType().equals(Constants.ROLE_XSB_CODE)) {
            condition.putIfAbsent("mediumUserId", loginUser.getId());
        }
        List<MediumVO> mediumList = mediumService.queryList(condition, condition.get("orderBy").toString(), condition.get("sortBy").toString().equals("ASC") ? SqlOrderEnum.ASC : SqlOrderEnum.DESC);
        List<Object> excelVOList = new ArrayList<>();
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MediumVO medium : mediumList) {
            MediumVideoExcelVO excelVO = new MediumVideoExcelVO();
            excelVO.setId(medium.getId());
            excelVO.setLabel(medium.getLabel());
            excelVO.setName(medium.getName());
            excelVO.setFansSheets(medium.getFansSheets());
            excelVO.setManRatio(medium.getManRatio());
            excelVO.setHeadLineQuoted(medium.getHeadLineQuoted());
            excelVO.setSecondLineQuoted(medium.getSecondLineQuoted());
            excelVO.setThirdLineQuoted(medium.getThirdLineQuoted());
            excelVO.setTailLineQuoted(medium.getTailLineQuoted());
            excelVO.setHeadLineCost(medium.getHeadLineCost());
            excelVO.setSecondLineCost(medium.getSecondLineCost());
            excelVO.setThirdLineCost(medium.getThirdLineCost());
            excelVO.setTailLineCost(medium.getTailLineCost());
            excelVO.setCreateUserName(medium.getCreateUserName());
            if (medium.getBillPoint() < 0) {
                excelVO.setBillPoint("普票" + (-medium.getBillPoint()) + "%");
            } else if (medium.getBillPoint() == 0) {
                excelVO.setBillPoint("不含票");
            } else {
                excelVO.setBillPoint("专票" + medium.getBillPoint() + "%");
            }
            excelVO.setBillPoint(dateTimeFormat.format(medium.getCreateDate()));
            excelVO.setRefuseType(medium.getRefuseType());
            excelVO.setCreateUserName(medium.getCreateUserName());
            excelVO.setUpdateDate(dateTimeFormat.format(medium.getUpdateDate()));
            excelVO.setOrderCount(medium.getOrderCount());
            excelVO.setCreateDesc(medium.getCreateDesc());
            excelVOList.add(excelVO);
        }
        String[] fieldTitle = {"视频号编号", "视频号类别", "视频号名称", "粉丝数量(万)", "粉丝年龄段", "男粉比例", "直发执行价", "链接执行价", "直发+链接执行价", "原创视频执行价",
                "直发成本价", "链接成本价", "直发+链接成本价", "原创视频成本价", "发票税点", "拒接广告类型", "对接员工", "更新时间", "合作排期数", "备注信息"};
        int[] fieldWidth = {10, 15, 20, 10, 10, 10, 10, 10, 10,
                10, 10, 10, 10, 10, 10, 40, 10, 20, 10, 40};
        ExcelExportUtil.export("视频号列表", fieldTitle, fieldWidth, excelVOList, response);
    }
}
